import '@/utils/cesiumfabric/WallDiffuseMaterialProperty.js'
let viewer;
let dataSource1 = new Cesium.CustomDataSource("dataSource1"); //自定义一个名为dataSource1的空数据集
export default {
  initMap(name) {
    viewer = new Cesium.Viewer(name, {
      animation: false,
      baseLayerPicker: false,
      fullscreenButton: false,
      geocoder: false,
      homeButton: false,
      infoBox: false,
      sceneModePicker: false,
      selectionIndicator: false,
      timeline: false,
      navigationHelpButton: false,
      navigationInstructionsInitiallyVisible: false,
      preserveDrawingBuffer: true,
      sceneMode: Cesium.SceneMode.COLUMBUS_VIEW, //哥伦布试图
      mapMode2D: Cesium.MapMode2D.ROTATE,
      //scene3DOnly: true,
      showAnimate: false,
      contextOptions: {
        webgl: {
          alpha: true,
          depth: false,
          stencil: true,
          antialias: true,
          premultipliedAlpha: true,
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: true,
        },
        allowTextureFilterAnisotropic: true,
      },
      // terrainProvider: Cesium.createWorldTerrain(),
      baseLayer: new Cesium.ImageryLayer(
        new Cesium.WebMapTileServiceImageryProvider({
          url: "http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=1d109683f4d84198e37a38c442d68311",
          layer: "tdtBasicLayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",
          credit: "",
          subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          maximumLevel: 18,
        })
      ),
    })
    window.viewer = viewer;
    viewer.map = {}
    // 屏蔽天空盒
    viewer.scene.skyBox.show = false;
    viewer.scene.backgroundColor = new Cesium.Color(0.0, 0.0, 0.0, 0.0); 
    viewer.scene.screenSpaceCameraController.enableTranslate = false; //屏蔽鼠标平移
    viewer.scene.screenSpaceCameraController.enableZoom = false; //屏蔽鼠标缩放
    // viewer.scene.screenSpaceCameraController.enableTilt = false; //屏蔽鼠标倾斜



    // 去除超图图标
    viewer._cesiumWidget._creditContainer.style.display = "none";
    return viewer
  },
  loadArea() {
    // viewer.scene.morphToColumbusView(0.5);//使用这句设置哥伦布视图后相机的scene.camera.setView，flyTo方法都失效
    const layer = viewer.imageryLayers.get(0);
    layer.alpha = 0;
    viewer.scene.globe.translucency.enabled = true; // 开启地表透明
    viewer.scene.globe.baseColor = new Cesium.Color(0.0, 0.0, 0.0, 0) // 把地球背景色透明
    viewer.scene.globe.undergroundColor = undefined;
    //viewer.scene.backgroundColor = Cesium.Color.TRANSPARENT;
    viewer.scene.backgroundColor = new Cesium.Color(0.0, 0.0, 0.0, 0);
    viewer.scene.globe.translucency.backFaceAlpha = 0.0;
    viewer.scene.screenSpaceCameraController.tiltEventTypes = [
      Cesium.CameraEventType.PINCH, 
      Cesium.CameraEventType.RIGHT_DRAG // 鼠标右键移动地图
    ];
    if (viewer.dataSources._dataSources.length < 1) {
      // 加载中国地图,叠加三次实现立体效果
      this.drawArea(
        {
          height: 190000,
          color: 'rgba(15, 89, 139, 1)',
          isOutLine: true,
          outlineWidth: 5,
          outlineColor: '#5a8690',
        }
      );
      this.drawArea(
        {
          extrudedHeight: 120000,
          height: 170000,
          color: 'rgba(10, 73, 125, 1)',
          WallColor: 'rgba(10, 73, 125, 1)',
          isOutLine: false,
        }
      );
      this.drawArea(
        {
          extrudedHeight: 50000,
          height: 190000,
          color: 'rgba(37, 94, 122, 1)',
          WallColor: 'rgba(37, 94, 122, 1)',
        }
      );
    }

    // viewer.entities.add({
    //   name: "立体墙效果",
    //   wall: {
    //     positions: Cesium.Cartesian3.fromDegreesArrayHeights([
    //       -107.0,
    //       43.0,
    //       100000.0,
    //       -97.0,
    //       43.0,
    //       100000.0,
    //       -97.0,
    //       40.0,
    //       100000.0,
    //       -107.0,
    //       40.0,
    //       100000.0,
    //       -107.0,
    //       43.0,
    //       100000.0,
    //     ]),
    //     // 设置高度
    //     //maximumHeights: new Array(positions.length).fill(50),
    //     //minimunHeights: new Array(positions.length).fill(0),
    //     // 扩散墙材质
    //     material: new Cesium.WallDiffuseMaterialProperty({
    //       color: new Cesium.Color("1.0, 1.0, 01.0, 1.0"),
    //       duration: 3000
    //     }),
    //   }
    // });

  },
  // 绘制中国地图
  drawArea(obj) {
    const promise = Cesium.GeoJsonDataSource.load("/topojson/china.topojson");
    promise.then(function (dataSource) {
      viewer.dataSources.add(dataSource);
      // let heading = Cesium.Math.toRadians(0);
      // let pitch = Cesium.Math.toRadians(-80);
      // viewer.zoomTo(dataSource, new Cesium.HeadingPitchRange(heading,  pitch, 0));
      viewer.scene.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(105, 30, 12000000.0),
        orientation: {
          heading: Cesium.Math.toRadians(0), // 水平旋转  -正北方向
          pitch: Cesium.Math.toRadians(-90), // 上下旋转  --俯视朝向
          roll: 0
        }
      })
      const entities = dataSource.entities.values;
      const colorHash = {};
      for (let i = 0; i < entities.length; i++) {
        const entity = entities[i];
        entity.polygon.disableDepthTestDistance = Number.POSITIVE_INFINITY;
        const name = entity.name;
        let color = colorHash[name];
        if (!color) {
          color = Cesium.Color.fromCssColorString(obj.color);
          colorHash[name] = color;
        }
        //Set the polygon material to our random color.
        entity.polygon.material = color;
        if(obj.WallColor) {//立体墙颜色
          entity.polygon.material = new Cesium.WallDiffuseMaterialProperty({
            color: Cesium.Color.fromCssColorString(obj.WallColor)
          })
        }
        //Remove the outlines.
        // 是否展示区划分界线
        entity.polygon.outline = obj.isOutLine;
        if(obj.isOutLine) {
          entity.polygon.outlineColor = Cesium.Color.fromCssColorString(obj.outlineColor);
          entity.polygon.outlineWidth = obj.outlineWidth;
        }
        if(obj.extrudedHeight) entity.polygon.extrudedHeight = obj.extrudedHeight;
        if(obj.height) entity.polygon.height = obj.height;
      }
    });
  },
  // 栽点
  // addPoint() {
  //   let pointList = [
  //     {id:1,lon:109.86,lat:31.10,city:'巫山'},
  //     {id:2,lon:109.52,lat:31.06,city:'奉节'},
  //     {id:3,lon:108.89,lat:30.99,city:'云阳'},
  //     {id:4,lon:108.89,lat:30.91,city:'云阳'},
  //     {id:5,lon:108.81,lat:29.53,city:'巫山'},
  //     {id:6,lon:116.38,lat:39.9,city:'天安门'},
  //     {id:7,lon:116.3,lat:39.95,city:'北区'}
  //   ]
  //   let dataSourcePromise;
  //   let img_path = require('@/assets/images/icon_jrts.png')
  //   for (let i = 0; i < pointList.length; i++) {
  //     // 对实体进行标注
  //     var item = pointList[i]; // 遍历获取每一条point数据，假设item是个对象
  //     dataSource1.entities.add(new Cesium.Entity({
  //       name: 'point'+i*100,
  //       position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat,200000), //从item对象获取经纬度
  //       billboard: {
  //         show: true,
  //         image: img_path,
  //         horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
  //         verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
  //         scale: 1,   // 标注点icon缩放比例
  //         width: 20,  // 设置标注点icon的高和宽，单位默认时px
  //         height: 20,
  //       },
  //       // 文本
  //       // label: {
  //       //   show: true, //是否显示标注点文本
  //       //   scale: 0.5, //这里非常巧妙的先将字体大小放大一倍在缩小一倍
  //       //   font: "normal 24px MicroSoft YaHei", //字体
  //       //   fillColor: Cesium.Color.BLUE.withAlpha(0.7),  //字体颜色
  //       //   text: item.city, //从接口获取点的标记文本
  //       //   pixelOffset: new Cesium.Cartesian2(0, -50), //文字显示的偏移量
  //       //   horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平居中
  //       //   verticalOrigin: Cesium.VerticalOrigin.CENTER, //垂直居中
  //       //   style: Cesium.LabelStyle.FILL, 
  //       //   showBackground: true,  //设置文本背景
  //       //   backgroundColor: Cesium.Color.fromCssColorString("#66ffff") //设置文本背景颜色,
  //       //   // backgroundColor: Cesium.Color.GRAY.withAlpha(0.6) 
  //       // }
  //     }))
  //   }
  //   dataSourcePromise = viewer.dataSources.add(dataSource1);
  //   this.combineListener();

  //   let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  //   // 鼠标移动事件
  //   handler.setInputAction(function (movement) {
  //     var pickedPrimitive = viewer.scene.pick(movement.endPosition);
  //     var pickedEntity = (Cesium.defined(pickedPrimitive)) ? pickedPrimitive.id : undefined;
  //     if (Cesium.defined(pickedEntity)) {
  //       if (viewer._container.style.cursor != "pointer") {
  //         viewer._container.style.cursor = "pointer";
  //       }
  //     } else {
  //       viewer._container.style.cursor = "default";
  //     }
  //   }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  //   // 鼠标左键点击事件
  //   handler.setInputAction(function (event) {
  //     let pickedEntity = viewer.scene.pick(event.position);
  //     if (pickedEntity) {
  //       const targetPoint = pickedEntity.id[0];
  //       targetPoint && viewer.flyTo(targetPoint, {
  //         offset: {
  //           heading: Cesium.Math.toRadians(0),
  //           pitch: Cesium.Math.toRadians(-75),
  //           range: 20000
  //         }
  //       });
  //     }
      
  //   }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  //   return dataSourcePromise
  // },
}